<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="initParam" :inline="true">
        <el-form-item label="设备类型">
          <el-select
            v-model="initParam.type1"
            placeholder="请选择设备类型"
            clearable
            @change="deviceTypeChage"
          >
            <el-option
              v-for="item in equipTypeList"
              :key="`${item.id}`"
              :label="`${item.equipTypeName}`"
              :value="`${item.id}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备">
          <el-select
            v-model="initParam.deviceId"
            placeholder="请选择设备"
            clearable
            @change="deviceChage"
          >
            <el-option
              v-for="item in equipList"
              :key="`${item.id}`"
              :label="`${item.equipName}`"
              :value="`${item.id}`"
            />
            <template #append>
              <el-button :icon="Search" />
            </template>
          </el-select>
        </el-form-item>

        <el-form-item label="监控参数">
          <el-select
            v-model="initParam.paramName"
            placeholder="请选择监控参数"
            clearable
            @change="changeParam"
          >
            <el-option
              v-for="item in collectList"
              :key="`${item.parameterName}`"
              :label="`${item.parameterDesc}`"
              :value="`${item.parameterName}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="采样间隔">
          <el-input
            style="width: 60px"
            v-model="initParam.interval"
            placeholder="请输入采样间隔(数字)"
          />
          <el-select
            style="width: 60px"
            v-model="initParam.type"
            placeholder="请选择采样单位"
            clearable
          >
            <el-option
              v-for="item in timeSCADA"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="X轴坐标">
          <el-select v-model="x" placeholder="请选择X轴坐标" clearable>
            <el-option
              v-for="item in XList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="统计时间">
          <el-date-picker
            v-model="initParam.alarmTimeSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getalarmTime"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchEcharts">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <!-- <h1>摩擦系数</h1> -->

      <div ref="chart" style="width: 100%; height: 380px"></div>

      <el-table
        style="margin-top: 10px"
        ref="dataTableRef"
        v-loading="loading"
        :data="
          getEchartsTable.slice(
            (currentPage - 1) * pageSize,
            currentPage * pageSize
          )
        "
        highlight-current-row
        border
      >
        <el-table-column
          label="采集时间"
          prop="collectionTime"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          :label="`${initParam.paramDesc}`"
          prop="data"
          min-width="100"
          align="center"
        />
      </el-table>

      <div class="block" style="margin-top: 15px">
        <el-pagination
          align="center"
          :background="true"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="getEchartsTable.length"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import * as echarts from "echarts";
import { Search } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import Big from "big.js";

defineOptions({
  name: "IOTSCAALARMRECORD",
  inheritAttrs: false,
});

// 获取当前时间及当前时间的前一个小时
const getTimeStart = () => {
  let midnight = dayjs(new Date().getTime() - 1000 * 60 * 60).format(
    "YYYY-MM-DD HH:mm:ss"
  );
  console.log(midnight);
  return midnight;
};

// 初始参数
const initParam = reactive({
  deviceCode: "",
  deviceId: "",
  paramName: "",
  paramDesc: "",
  type1: "",
  type: "1",
  interval: "1",
  x: "0",
  startTime: getTimeStart(),
  endTime: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),
  alarmTimeSearch: [
    getTimeStart(),
    dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),
  ],
});

// 表格操作 Hooks
const { loading }: any = useTable();

// 前端手动分页代码
const currentPage = ref(1); // 当前页码
const total = ref(10); // 总条数
const pageSize = ref(5); // 每页的数据条数

const handleSizeChange = (val) => {
  currentPage.value = 1;
  pageSize.value = val;
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
};
// 获取折线图数据
const getEchartsTable = ref([]);
async function getInfo() {
  console.log("initParam", initParam);
  request({
    url: `/iotadmin/monitorTend/statistics`,
    method: "post",
    data: {
      deviceCode: `${initParam.deviceCode}`,
      paramName: `${initParam.paramName}`,
      type: `${initParam.type}`,
      interval: `${initParam.interval}`,
      startTime: `${initParam.startTime}`,
      endTime: `${initParam.endTime}`,
      alarmTimeSearch: `${initParam.alarmTimeSearch}`,
    },
  })
    .then((res) => {
      getEchartsTable.value = res.data.data;
      if (res.data.datalenth > 5000) {
        ElMessage.success("因查询数据过多，只展示前五千条");
      }
      echartList();
    })
    .catch((res) => {
      console.log(res);
    });
}

// X轴坐标
const x = ref("0");
const XList = ref([
  { label: "时间", value: "0" },
  { label: "序号", value: "1" },
]);

// 定义单位
const timeSCADA = [
  { label: "秒", value: "1" },
  { label: "分", value: "2" },
  { label: "时", value: "3" },
];
// 处理时间
function getalarmTime(data: any) {
  if (data) {
    console.log(data);

    initParam.startTime = data[0];
    initParam.endTime = data[1];
  } else {
    initParam.startTime = "";
    initParam.endTime = "";
  }
}

// 获取设备类型下拉框
const equipTypeList: any = ref([]);
const getEquipTypeList = async () => {
  const res = await request({
    url: "/iotadmin/scaequiptype/getlist",
    method: "post",
    data: {},
  });
  if (res.code === 200) {
    equipTypeList.value = res.data;
  }
};

// 点击设备类型下拉框时，根据选中的值赋给initParam
const equipList: any = ref([]);
const deviceTypeChage = async (value: any) => {
  if (initParam.type1) {
    initParam.deviceId = "";
    initParam.deviceCode = "";
    initParam.paramName = "";
    initParam.paramDesc = "";
    collectList.value = [];
    const res = await request({
      url: "/iotadmin/scaequipinfo/getlist",
      method: "post",
      data: { equipTypeId: initParam.type1 },
    });
    if (res.code === 200) {
      equipList.value = res.data;
    }
  } else {
    equipList.value = [];
    initParam.deviceId = "";
    initParam.deviceCode = "";
    collectList.value = [];
  }
};

// 点击设备下拉框时
const collectList: any = ref([]);
const deviceChage = async () => {
  if (initParam.deviceId) {
    initParam.paramName = "";
    initParam.paramDesc = "";
    initParam.deviceCode = "";
    collectList.value = [];
    const res = await request({
      url: `/iotadmin/scaequipinfo/get/${initParam.deviceId}`,
      method: "get",
    });
    if (res.code === 200) {
      collectList.value = res.data.scaEquipCollectionParams;
      equipList.value.forEach((element) => {
        if (element.id === initParam.deviceId) {
          initParam.deviceCode = element.equipCode;
        }
      });
    }
  } else {
    collectList.value = [];
    initParam.deviceCode = "";
    initParam.paramName = "";
    initParam.paramDesc = "";
  }
};

// 点击参数下拉框时并赋值上下限
const upperLimitValue = ref();
const lowerLimitValue = ref();
const changeParam = (e) => {
  if (e) {
    collectList.value.forEach((element) => {
      if (element.parameterName === e) {
        console.log("element.upperLimitValue", element);
        console.log("element.lowerLimitValue", element.lowerLimitValue);
        initParam.paramDesc = element.parameterDesc;
        upperLimitValue.value = element.upperLimitValue;
        lowerLimitValue.value = element.lowerLimitValue;
      }
    });
  }
};
// 点击搜索
const searchEcharts = () => {
  getInfo();
  echartList();
};
// 点击重置按钮
const reset = () => {
  initParam.type1 = "";
  initParam.type = "1";
  initParam.deviceId = "";
  initParam.paramName = "";
  initParam.paramDesc = "";
  equipList.value = [];
  collectList.value = [];
  initParam.interval = "1";
  x.value = "0";
  getInfo();
  echartList();
  (initParam.startTime = getTimeStart()),
    (initParam.endTime = dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss")),
    (initParam.alarmTimeSearch = [
      getTimeStart(),
      dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),
    ]);
};
// echarts图行数据
const chart = ref(null);

// 计算y轴最小值
function computedMin(minValue: number, maxValue: number) {
  if (lowerLimitValue.value && lowerLimitValue.value < minValue) {
    return lowerLimitValue.value;
  } else if (minValue || maxValue) {
    const result = new Big(minValue)
      .minus(new Big(maxValue).minus(minValue).div(10))
      .toNumber()
      .toFixed(2);
    if (result < 0 && minValue >= 0) {
      return 0;
    } else {
      return result;
    }
  } else {
    return minValue;
  }
}

// 计算y轴最大值
function computedMax(maxValue: number, minValue: number) {
  if (!upperLimitValue.value && maxValue) {
    return new Big(maxValue)
      .plus(new Big(maxValue).minus(minValue).div(10))
      .toNumber()
      .toFixed(2);
  } else if (
    (minValue || maxValue) &&
    upperLimitValue.value &&
    upperLimitValue.value < maxValue
  ) {
    return new Big(maxValue)
      .plus(new Big(maxValue).minus(minValue).div(10))
      .toNumber()
      .toFixed(2);
  } else {
    return upperLimitValue.value;
  }
}

const echartList = () => {
  let option = {
    title: {
      text: `${initParam.paramDesc}`,
      // left: "1%",
    },
    tooltip: {
      trigger: "axis",
    },
    grid: {
      left: "5%",
      height: "auto",
      minHeight: 380, // 单位为像素
      bottom: "26%",
    },
    xAxis: {
      type: "category",
      data: getEchartsTable.value?.map(function (item: any, index) {
        return x.value == "0" ? item.collectionTimeXdata : item.index;
      }),
      axisLabel: {
        interval: "auto", // 坐标刻度之间的显示间隔，默认就可以了
        rotate: 38, // 调整数值改变倾斜的幅度（范围-90到90）
      },
      axisTick: {
        alignWithLabel: true, // true：标签位于刻度线正下方；false：标签位于2个刻度线中间
      },
    },
    yAxis: {
      type: "value", // 坐标轴类型:数值轴
      // name: "湿度", // 坐标轴名称
      position: "left", // 坐标轴位置:左侧
      min: function (value: any) {
        return computedMin(value.min, value.max);
      },
      max: function (value: any) {
        return computedMax(value.max, value.min);
      },
      // max: 1000,           // 坐标轴最大值(当前被注释掉)
      // min: 59,             // 坐标轴最小值(当前被注释掉)
      // axisLabel: {
      //   interval: "auto", // 坐标刻度之间的显示间隔，默认就可以了
      //   // 调整数值改变倾斜的幅度（范围-90到90）
      // },
      // interval: "auto", // 坐标轴刻度间隔(当前被注释掉)
      offset: 0, // 坐标轴相对于默认位置的偏移:无偏移
      axisLine: {
        show: true, // 是否显示坐标轴线
        lineStyle: {
          color: "#6e7079", // 坐标轴线颜色:使用颜色数组的第一个颜色
        },
      },
      axisTick: {
        show: true,
      },
      splitLine: {
        show: true, // 是否显示分隔线
        lineStyle: {
          // color: "red",      // 分隔线颜色(当前被注释掉)
          // width: 4,          // 分隔线宽度(当前被注释掉)
          type: "dotted", // 分隔线类型:点线
        },
      },
    },

    // toolbox: {
    //   right: 10,
    //   feature: {
    //     dataZoom: {
    //       yAxisIndex: "none",
    //     },
    //     restore: {},
    //     saveAsImage: {},
    //   },
    // },
    dataZoom: [
      {
        bottom: "20px",
        startValue: `${initParam.startTime}`,
      },
      {
        type: "inside",
      },
    ],
    // visualMap: {
    //   top: 50,
    //   right: 10,
    //   pieces: [
    //     {
    //       gt: 0,
    //       lte: 50,
    //       color: "#93CE07",
    //     },
    //     {
    //       gt: 50,
    //       lte: 100,
    //       color: "#FBDB0F",
    //     },
    //     {
    //       gt: 100,
    //       lte: 150,
    //       color: "#FC7D02",
    //     },
    //     {
    //       gt: 150,
    //       lte: 200,
    //       color: "#FD0100",
    //     },
    //     {
    //       gt: 200,
    //       lte: 300,
    //       color: "#AA069F",
    //     },
    //     {
    //       gt: 300,
    //       color: "#AC3B2A",
    //     },
    //   ],
    //   outOfRange: {
    //     color: "#999",
    //   },
    // },
    series: {
      name: `${initParam.paramDesc}`,
      type: "line",
      data: getEchartsTable.value?.map(function (item: any, index) {
        return item.data;
      }),
      markLine: {
        silent: true,
        lineStyle: {
          color: "red",
        },
        symbol: ["none", "none"],
        data: [
          {
            yAxis: `${upperLimitValue.value}`,
          },
          {
            yAxis: `${lowerLimitValue.value}`,
          },
        ],
      },
    },
  };
  const myChart = echarts.init(chart.value);
  myChart.setOption(option);
};

onMounted(() => {
  echartList();
  getEquipTypeList();
});
</script>
<style lang="scss" scoped>
.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
</style>
